package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜品管理  业务层
 *
 * @Author mr.li
 * @Date 2025/7/8 11:37
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    /**
     * 新增菜品
     *
     * @param dishDTO 菜品信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();

        //拷贝数据
        BeanUtils.copyProperties(dishDTO,dish);

        dishMapper.save(dish);
        //口味信息，需要取出来添加到另一个表中
        List<DishFlavor> flavors = dishDTO.getFlavors();


        if (!flavors.isEmpty()){
            flavors.forEach(s -> s.setDishId((Long) dish.getId()));
            dishFlavorMapper.save(flavors);
        }

    }

    /**
     * 分页查询菜品
     *
     * @param dishPageQueryDTO 分页数据
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        List<DishVO> dishList =  dishMapper.pageQuery(dishPageQueryDTO);
        Page<DishVO> page = (Page<DishVO>) dishList;

        return new PageResult(page.getTotal(),page.getResult());


    }


    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 删除菜品
     *
     * @param ids 菜品id集合
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        //- 起售中的菜品不能删除
        //- 被套餐关联的菜品不能删除
        //- 删除菜品后，关联的口味数据也需要删除掉


        //需要分别删除菜品的口味和  菜品
        if (!CollectionUtils.isEmpty(ids)){
            //1.查看是否起售，如果有一个起售菜品，就都不能删除
            Integer countStatus = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
            //1.1有起售菜品,就抛出异常  "起售中的菜品不能删除";
            if (countStatus > 0) {
                throw  new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            //2. 查看是否关联了商品
            Integer countRelation = setmealDishMapper.selectCountByIdsRelation(ids);//&&&relation关系，亲戚，联系
            //2.1有关联的菜品，就抛出异常  "被套餐关联的菜品不能删除"
            if(countRelation>0  ){
                throw  new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL   );
            }

            //3.先删除菜品
            dishMapper.deleteByIds(ids);

            //4.再根据id删除对应的口味
            dishFlavorMapper.deleteDishByIds(ids);

        }


    }

    /**
     * 根据id查询菜品信息
     *
     * @param id
     * @return 菜品信息
     */
    @Override
    public DishVO getById(Integer id) {

        return dishMapper.getById(id);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO 菜品信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DishDTO dishDTO) {
        //更新菜品信息  和 口味信息
        //1. 拷贝菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //2. 更新菜品信息，将id信息添加到
         dishMapper.update(dish);

        //2. 判断是否有口味信息，有的话就取出来
        List<DishFlavor> flavors = dishDTO.getFlavors();

        Long id = dish.getId();
        ArrayList<Long> ids = new ArrayList<>();
        //3.1 开始删除口味信息
        dishFlavorMapper.deleteDishByIds(ids);

        // 3.2 如果新的口味信息不为空，就添加新的
        if(!CollectionUtils.isEmpty(flavors)){

            flavors.forEach(f->{f.setDishId(id);});

            //3.3 重新添加口味信息
            dishFlavorMapper.save(flavors);

        }




    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
